package com.ckd.flyingtrip.widge;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolManager {
	private ExecutorService service;

	private ThreadPoolManager() {
		service = Executors.newFixedThreadPool(30);
	}

	private static ThreadPoolManager manager;
	private Future<?> futrue;

	public static ThreadPoolManager getInstance() {
		if (manager == null) {
			manager = new ThreadPoolManager();
		}
		return manager;
	}

	public void addTask(Runnable runnable) {
		futrue = service.submit(runnable);
	}

	public void cancelTask() {
		if (futrue != null) {
			futrue.cancel(true);
		}
	}

	/**
	 * shutdown()
	 * 作为函数，当然是立即执行，也即是不再接受新任务了；但是它即不会强行终止正在执行的任务，也不会取消已经提交的任务。也就是说之前提交的5个任务
	 * ，仍然会执行完毕，且跟主线程生命周期无关
	 */
	public void shutDown() {
		if (service != null) {
			service.shutdown();
		}
		manager = null;
	}

	/**
	 * 1）、对于尚未执行的任务，全部取消掉； 2）、对于正在执行的任务，发出interrupt()。
	 */
	public void shutDownNow() {
		try {
			if (service != null) {
				service.shutdownNow();
			}
			manager = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
